﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace DotNETX.CommonWcfHost
{
    public class WcfAssemblyLoader
    {
        public List<Assembly> LoadedAssemblys { get; protected set; }

        public void LoadAssemblyInFolder(string folder)
        {
            if(!Path.IsPathRooted(folder) && !Directory.Exists(folder))
            {
                folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folder);
            }
            if (Directory.Exists(folder))
            {
                FileInfo[] files = new DirectoryInfo(folder).GetFiles();
                foreach (FileInfo file in files)
                {
                    if (file.Extension != null && file.Extension.ToLower() == ".dll")
                    {
                        LoadAssembly(file.FullName);
                    }
                }
            }
        }

        public bool LoadAssembly(string filepath)
        {
            if (null == LoadedAssemblys) LoadedAssemblys = new List<Assembly>();
            // 检查文件
            if (File.Exists(filepath))
            {
                FileInfo file = new FileInfo(filepath);
                var loaded = LoadedAssemblys.Find((asm) => { return asm.Location == file.FullName; }) != null;
                // 未加载
                if (!loaded) try
                    {
                        Assembly assembly = Assembly.Load(AssemblyName.GetAssemblyName(filepath));
                        //Assembly assembly = Assembly.LoadFrom(filepath);
                        // 检查加载是否成功
                        if (null != assembly)
                        {
                            LoadedAssemblys.Add(assembly);
                            return true;
                        }
                    }
                    catch
                    {
                    }
            }
            return false;
        }
    }
}
